import clientPromise from '@/libs/mongoClient';
import { buildPaginationResponse } from '@/libs/pagination';
import { NextApiResponse } from '@/libs/apiResponse';
import { Document, Filter, ObjectId } from 'mongodb';
import { type NextRequest } from 'next/server';
import { z } from 'zod';

export interface PlanDocument {
  _id: string;
  template: string;
  version: string;
  parameter: Parameter[];
  file: FileReference;
  creator: string;
  status: 'private' | 'public';
  createdAt: Date;
  updatedAt: Date;
}

export interface Parameter {
  key: string;
  value: any;
  type: 'string' | 'number' | 'boolean' | 'date' | 'object' | 'array';
  description?: string;
}

interface FileReference {
  filename: string;
  path: string;
  bucket: string;
  url: string;
  createdAt: Date;
}

// 假设结构如下（你可根据实际结构修改）
const ParameterSchema = z.object({
  key: z.string(),
  type: z.string(),
  value: z.any(), // 根据需要可更严格约束类型
});

const CreatePlanSchema = z.object({
  template: z.string(),
  version: z.string(),
  parameter: z.array(ParameterSchema),
  file: z.any(),
  creator: z.string(),
  status: z.enum(['private', 'public']),
});

// POST /api/plans 生成方案
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const validationResult = CreatePlanSchema.safeParse(body);

    if (!validationResult.success) {
      return NextApiResponse.badRequest(validationResult.error.message);
    }

    const planData = validationResult.data;

    const db = (await clientPromise).db('ruanzhu_template');

    const newPlan = {
      ...planData,
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const result = await db.collection('plan').insertOne(newPlan);

    return NextApiResponse.success(
      {
        planId: result.insertedId.toString(),
      },
      '创建成功'
    );
  } catch (error) {
    console.error('出错了:', error);

    return NextApiResponse.serverError('服务器内部错误');
  }
}

const QuerySchema = z.object({
  id: z.string().optional(),
  page: z.coerce.number().min(1).default(1),
  pageSize: z.coerce.number().min(1).max(100).default(10),
  search: z.string().optional(),
  sortBy: z.string().optional(),
  sortOrder: z.enum(['asc', 'desc']).default('desc'),
});

// GET /api/plans 获取历史方案
export async function GET(request: NextRequest) {
  try {
    const searchParams = Object.fromEntries(request.nextUrl.searchParams);
    const query = QuerySchema.parse(searchParams);

    const db = (await clientPromise).db('ruanzhu_template');

    const filter: Filter<Document> = {};

    if (query.search && query.search.trim()) {
      const searchRegex = new RegExp(query.search.trim(), 'i');

      filter.$or = [
        { template: searchRegex }, // 在标题中搜索
        { creator: searchRegex }, // 在内容中搜索
        { parameter: { $in: [searchRegex] } }, // 在标签数组中搜索
      ];
    }

    const plans = await db
      .collection('plan')
      .find(filter)
      .skip((query.page - 1) * query.pageSize)
      .limit(query.pageSize)
      .sort({
        createdAt: -1,
      })
      .toArray();
    const total = await db.collection('plan').countDocuments();

    const data = buildPaginationResponse(plans, total, {
      page: query.page,
      pageSize: query.pageSize,
    });

    return NextApiResponse.success(data, '获取成功');
  } catch (error) {
    console.error(error);

    return NextApiResponse.serverError('服务器内部错误');
  }
}

const DeleteSchema = z.object({
  id: z.string().min(1, 'ID不能为空'),
});

// DELETE /api/plans 删除方案
export async function DELETE(request: NextRequest) {
  try {
    const searchParams = Object.fromEntries(request.nextUrl.searchParams);
    const validationResult = DeleteSchema.safeParse(searchParams);

    if (!validationResult.success) {
      return NextApiResponse.badRequest(
        validationResult.error.issues[0].message
      );
    }

    const { id } = validationResult.data;

    const db = (await clientPromise).db('ruanzhu_template');

    // 检查方案是否存在
    const existingPlan = await db
      .collection('plan')
      .findOne({ _id: new ObjectId(id) });

    if (!existingPlan) {
      return NextApiResponse.notFound('方案不存在');
    }

    // 删除方案
    const result = await db
      .collection('plan')
      .deleteOne({ _id: new ObjectId(id) });

    if (result.deletedCount === 0) {
      return NextApiResponse.serverError('删除失败');
    }

    return NextApiResponse.success(
      {
        deletedId: id,
      },
      '删除成功'
    );
  } catch (error) {
    console.error('删除方案出错:', error);

    // 处理无效的 ObjectId 格式
    if (error instanceof Error && error.message.includes('ObjectId')) {
      return NextApiResponse.badRequest('无效的ID格式');
    }

    return NextApiResponse.serverError('服务器内部错误');
  }
}
